package main

import (
	"context"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"go.opentelemetry.io/contrib/instrumentation/github.com/labstack/echo/otelecho"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
	"log"
	"net/http"
)

func init() {
	client := otlptracegrpc.NewClient(
		otlptracegrpc.WithEndpoint("127.0.0.1:4317"),
		otlptracegrpc.WithInsecure(), // 如果是开发环境或不需要加密连接

	)
	exp, err := otlptrace.New(context.Background(), client)
	if err != nil {
		log.Fatalf("otlptrace.New: %v", err)
		return
	}

	res, err := resource.Merge(
		resource.Default(),
		resource.NewWithAttributes(
			semconv.SchemaURL,
			semconv.ServiceName("app2"),
		),
	)
	if err != nil {
		log.Fatalf("otlptrace.New: %v", err)
		return
	}

	// 创建追踪器提供者
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(exp),
		sdktrace.WithResource(res),
	)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})

}

func main() {

	e := echo.New()

	e.Use(middleware.Logger())
	e.Use(otelecho.Middleware("service-name-app2"))

	e.GET("/app2", func(c echo.Context) error {

		//ctx := propagation.TraceContext{}.Extract(context.Background(), propagation.HeaderCarrier(c.Request().Header))
		//c.Request().WithContext(ctx)

		tracer := otel.Tracer("ServiceB")

		// 创建子 span
		//ctx, span := tracer.Start(ctx, "serviceb-span", trace.WithSpanKind(trace.SpanKindServer))
		_, span := tracer.Start(c.Request().Context(), "serviceb-span", trace.WithSpanKind(trace.SpanKindServer))
		defer span.End()

		span.SetAttributes(attribute.String("app2", "app2"))

		log.Println("calling app2")
		return c.JSON(http.StatusOK, map[string]interface{}{
			"name": "app2",
		})
	})

	err := e.Start(":8082")
	if err != nil {
		log.Fatal(err)
		return
	}

}
